﻿using System;
using System.Text;
using TI_BLE_HCI_ClientLib.BaseEntities;
using TI_BLE_HCI_ClientLib.GenericHCIEntities;
using TI_BLE_HCI_ClientLib.HCIBaseEntities;

namespace TI_BLE_HCI_ClientLib.HCICommands
{
    public class HCICommand_GATT_Find_By_Type_Value_Response : HCIVendorSpecificCommand
    {
        private const byte CMD = 0x07;

        public HCICommand_GATT_Find_By_Type_Value_Response(ushort connHandle, byte[] handlesInfo)
            : base(HCIVendorSpecificCommandCSG.ATT, CMD)
        {
            var pars = new BaseEntityParameter[2];

            pars[0] = new WordParameter(connHandle);
            pars[1] = new ByteArrayParameter(handlesInfo);

            base.addParameters(pars);
        }

        public HCICommand_GATT_Find_By_Type_Value_Response(ushort connHandle, HandlesInfo[] handlesInfoArray)
            : this(connHandle, getHandlesInfoArrayData(handlesInfoArray))
        { }


        static byte[] getHandlesInfoArrayData(HandlesInfo[] handlesInfoArray)
        {
            if (handlesInfoArray == null || handlesInfoArray.Length == 0) return new byte[0];

            var buf = new byte[handlesInfoArray.Length * 4];

            for(int i=0;i<handlesInfoArray.Length;i++)
            {
                Array.Copy(handlesInfoArray[i].ToByteArray(), 0, buf, i * 4, 4);
            }

            return buf;
        }

        public class HandlesInfo
        {
            ushort _foundAttributeHandle;
            ushort _handleGroupEndHandle;

            public HandlesInfo(ushort foundAttributeHandle, ushort handleGroupEndHandle)
            {
                _foundAttributeHandle = foundAttributeHandle;
                _handleGroupEndHandle = handleGroupEndHandle;
            }

            public byte Length
            {
                get
                {
                    return 4;
                }
            }

            public byte[] ToByteArray()
            {
                var buf = new byte[4];

                buf[0] = (byte)(_foundAttributeHandle & 0xFF);
                buf[1] = (byte)((_foundAttributeHandle >> 8) & 0xFF);

                buf[2] = (byte)(_handleGroupEndHandle & 0xFF);
                buf[3] = (byte)((_handleGroupEndHandle >> 8) & 0xFF);

                return buf;
            }
        }
    }
}
